package com.business;
/**
 *
 **/

import lombok.Data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author weiwei
 * @Date 2021-06-07 09:01
 * @description
 **/
@Data
public class OperationTime {

    private Date startTime;

    private Date endTime;

    /**
     * 将分散的时间合并
     * 如 11-13 13-15 变为11-15
     * @param intervals
     * @return
     */
    public List<OperationTime> merge(List<OperationTime> intervals) {
        List<OperationTime> result = new ArrayList<>();
        if (intervals == null || intervals.size() < 1) {
            return result;
        }
        int len = intervals.size();
        Date[] starts = new Date[len];
        Date[] ends = new Date[len];
        for (int i = 0; i < len; i++) {
            starts[i] = intervals.get(i).getStartTime();
            ends[i] = intervals.get(i).getEndTime();
        }
        Arrays.sort(starts);
        Arrays.sort(ends);
        for (int i = 0, j = 0; i < len; i++) {
            if (i == len - 1 || starts[i + 1].compareTo(ends[i]) > 0) {
                OperationTime operationTime = new OperationTime();
                operationTime.setStartTime(starts[j]);
                operationTime.setEndTime(ends[i]);
                result.add(operationTime);
                j = i + 1;
            }
        }
        return result;
    }


}
